/* 
 * Copyright (C) 2022 Leah Rowe <info@minifree.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "../include/lib/word.h"

int word(uint8_t** buffer, uint16_t pos16, uint8_t part)
{
	uint16_t value = 0;
	uint16_t pos8 = (pos16 << 1);
	uint16_t offset = pos8 + (part << 12);

	value |= (uint16_t)(*buffer)[offset];
	value |= (uint16_t)(*buffer)[offset+1] << 8;

	return value;
}

void setWord(uint8_t** buffer, uint16_t pos16, uint8_t part, uint16_t value)
{
	uint16_t pos8 = (pos16 << 1);
	uint16_t offset = pos8 + (part << 12);

	(*buffer)[offset] = (uint8_t)(value & 0xFF);
	(*buffer)[offset+1] = (uint8_t)(value >> 8);
}

void nvmDump(uint8_t** buffer, uint8_t part)
{
	uint16_t value;
	for (int i=0; i<8; i++) {
		printf("%07x ", i<<4);
		for (int j=0; j<8; j++) {
			value = word(buffer, ((i<<4)+(j<<1)) >> 1, part);
			for (int k=0; k<2; k++) {
				printf("%02x", (value>>((k^1)<<3)) & 0xFF);
			}
			printf(" ");
		}
		printf("\n");
	}
}

uint8_t partSpecified(char* strPart)
{
	if (strlen(strPart) != 1) return 2;
	if (strPart[0]<48 || strPart[0]>49) return 2;

	return (uint8_t)strPart[0] - 48;
}

